package com.thinkgem.jeesite.modules.sys.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.thinkgem.jeesite.common.persistence.BaseConstants;
import com.thinkgem.jeesite.common.utils.SessionUtils;
import com.thinkgem.jeesite.modules.sys.dao.SysOfficeMapper;
import com.thinkgem.jeesite.modules.sys.entity.SysOffice;
import com.thinkgem.jeesite.modules.sys.utils.SysCacheUtils;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author:Kongxiangsheng
 * @DesCription:
 * @Date:Created in 14:47 2018/8/14
 * @Modified By:
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysOfficeService extends ServiceImpl<SysOfficeMapper, SysOffice> implements IService<SysOffice> {

    public SysOffice get(String sysOfficeId) {
        // 先从缓存获取
        SysOffice sysOffice = SysCacheUtils.getSysOffice(sysOfficeId);
        if (null != sysOffice) {
            return sysOffice;
        }

        // 缓存中不存在，则从数据库获取
        sysOffice = this.baseMapper.selectById(sysOfficeId);
        if (null != sysOffice) {
            SysCacheUtils.putSysOffice(sysOffice.getId(), sysOffice);
        }
        return sysOffice;
    }

    public List<SysOffice> findList(Boolean isAll) {
        if (isAll != null && isAll) {
            return UserUtils.getAllOfficeList();
        } else {
            return UserUtils.getOfficeList();
        }
    }

    /**
     * 获取所有机构
     *
     * @return
     */
    public List<SysOffice> selectAll() {
        QueryWrapper queryWrapper = new QueryWrapper<SysOffice>();
        queryWrapper.orderByAsc(SysOffice.COL_PARENT_IDS);
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 获取机构及其下的组织机构
     *
     * @param id
     * @return
     */
    public List<SysOffice> selectWithChildren(String id) {
        if (StringUtils.isBlank(id)) {
            return new ArrayList<SysOffice>();
        }
        String param = "," + id + ",";
        QueryWrapper queryWrapper = new QueryWrapper<SysOffice>();
        queryWrapper.like(SysOffice.COL_PARENT_IDS, param);
        queryWrapper.or();
        queryWrapper.eq(SysOffice.COL_ID, id);
        queryWrapper.orderByAsc(SysOffice.COL_PARENT_IDS);
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 根据机构Id获取归属的公司（最下级）
     *
     * @param officeId
     * @return
     */
    public SysOffice getBelongCompany(String officeId) {
        SysOffice office = this.get(officeId);
        String ids = office.getParentIds() + officeId;
        return this.baseMapper.getLowestCompany(ids.split(","));
    }

    /**
     * 获取所有子机构
     *
     * @param id
     * @return
     */
    public List<SysOffice> selectChildren(String id) {
        if (StringUtils.isBlank(id)) {
            return new ArrayList<SysOffice>();
        }
        String param = "," + id + ",";
        QueryWrapper queryWrapper = new QueryWrapper<SysOffice>();
        queryWrapper.like(SysOffice.COL_PARENT_IDS, param);
        queryWrapper.orderByAsc(SysOffice.COL_PARENT_IDS);
        return this.baseMapper.selectList(queryWrapper);
    }

    /**
     * 获取机构名称全路径
     *
     * @param sysOfficeId
     * @return
     */
    public String getOfficeNamePath(String sysOfficeId) {
        SysOffice office = this.get(sysOfficeId);
        if (null == office) {
            return "";
        }

        List<String> nameList = Lists.newArrayList();
        for (String id : StringUtils.split(office.getParentIds(), ",")) {
            if (BaseConstants.ROOT_OFFICE_ID.equals(id)) {
                continue; // 过滤根节点
            }
            SysOffice parent = this.get(id);
            if (null == parent) {
                continue;
            }
            nameList.add(parent.getName());
        }
        nameList.add(office.getName());
        String namePath = StringUtils.join(nameList, "-");

        return namePath;
    }

    @Transactional(rollbackFor = Exception.class)
    public void checkAndSave(SysOffice sysOffice) {
        // 获取修改前的parentIds，用于更新子节点的parentIds
        String oldParentIds = sysOffice.getParentIds();

        // 设置新的parentIds
        if (StringUtils.isNotBlank(sysOffice.getParentId())) {
            SysOffice parentOffice = this.getById(sysOffice.getParentId());
            sysOffice.setParentIds(parentOffice.getParentIds() + parentOffice.getId() + ",");
        } else {
            sysOffice.setParentId("0");
            sysOffice.setParentIds("0,");
        }

        // 设置sort
        if (null == sysOffice.getSort()) {
            sysOffice.setSort(30);
        }
        // 设置机构级别
        if (null == sysOffice.getGrade()) {
            sysOffice.setGrade(sysOffice.getParentIds().split(",").length - 1);
        }

        if (StringUtils.isEmpty(sysOffice.getId())) {
            this.save(sysOffice);
        } else {
            this.updateById(sysOffice);

            // 更新所有子机构的parent_ids
            List<SysOffice> childrenList = this.selectChildren(sysOffice.getId());
            for (SysOffice child : childrenList) {
                child.setParentIds(child.getParentIds().replace(oldParentIds, sysOffice.getParentIds()));
                this.updateById(child);
            }
        }

        SessionUtils.removeAttrOfficeAll();
        SessionUtils.removeAttrOffice();
    }

    @Transactional(rollbackFor = Exception.class)
    public void delete(SysOffice sysOffice) {
        this.removeById(sysOffice.getId());
        SessionUtils.removeAttrOfficeAll();
        SessionUtils.removeAttrOffice();
    }

}
